<?php

namespace Plu\qdh\Services;

use Httpful\Request;
use Plu\qdh\Services\ServiceBase;
use Plu\qdh\Services\ThirdService;
use Plu\qdh\Services\PaymentService;
use Plu\qdh\Services\ProductService;
use Plu\qdh\Models\App\Project;
use Plu\qdh\Models\App\Platform;
use Plu\qdh\Models\App\Product;
use Plu\qdh\Models\App\Order;


class OrderService extends ServiceBase {

    private $_orderId;

    private $_productNo;

    private $_travateDate;

    public function setOrderId($orderId) {
        $this->_orderId = $orderId;
    }

    public function setUserAccount($userAccount) {
        $this->_userAccount = $userAccount;
    }

    public function setProductNo($productNo) {
        $this->_productNo = $productNo;
    }

    public function setTravateData($travateDate) {
        $this->_travateDate = $travateDate;
    }

    // 产品核销
    public function usedOrder($orderId) {
        $item  = Order::getItemByOrderId($orderId);
        $item->updateTime = time();
        $item->status = \OrderConst::ORDER_STATUS['used'];
        $item->save();
    }

    // 第三方出票
    public function publishOrder($orderId) {
        $item  = Order::getItemByOrderId($orderId);
        $item->status = \OrderConst::ORDER_STATUS['published'];
        $item->updateTime = time();
        $item->save();
    }

    // 第三方取消退票 
    public function notifyCancelOrder($orderId) {

        $item = Order::getItemByOrderId($orderId);
        $status = $item->status;

        // 预存款未付款第三方会取消订单
        if ($item->isPay == 1) {

            $payMentServer = new PaymentService;
            $payMentServer->setOrderId($item->orderId);
            $payMentServer->wechatRefound();

        } else {

            $item->updateTime = time();
            $item->status = \OrderConst::ORDER_STATUS['refind'];
            $item->save();
            
        }


    }

    // 获取订单详情
    public function getOrderDetail($orderId) {

        $item = Order::getItemById($orderId);
        
        if ($item) {

            $item->createTime   = date('Y-m-d H:i:s', $item->createTime);
            $item->travelDay    = date('Y-m-d H:i:s', $item->travelDay);
            $item->payLimitTime = date('Y-m-d H:i:s', $item->payLimitTime);
            $item->payTime      = $item->payTime?date('Y-m-d H:i:s', $item->payTime):"";

            $productNo      = $item->productNo;
            $productService = new ProductService;
            $productInfo = $productService->getProductDetail($productNo);
	        $redis = $this->getRedis('qdh');
	        $projectId   = $productInfo['projectId'];
            $redisKey    = sprintf(ProductService::PROJECT_INFO, $projectId);
            $projectInfo = $redis->get($redisKey);
            $projectInfo = json_decode($projectInfo, true);
            
	        $item = $item->toArray();

	        if((date("Y-m-d H:i:s", time()) >  $item['payLimitTime']) && $item['status'] = \OrderConst::ORDER_STATUS['wating']) {
                $item['status'] = (string) \OrderConst::ORDER_STATUS['expire'];
            }

            $item['refoundable']   = $productInfo['refoundable']; 
            
            if ($item->status == 0 || $item->status == 1 || $item->status == 9 ) {
                $item['refoundable'] = $productInfo['refoundable']; 
            } else {
                $item['refoundable'] = "0";
            }

            $item['projectPrompt'] = $projectInfo['projectPrompt'];
            $item['phone'] = $projectInfo['phone'];
            return $item;
        }
        
        return [];
    }

    // 获取用户订单
    public function getUserOrders($limit, $offset, $status) {

        $productService = new ProductService;
        $redis  = $this->getRedis('qdh');
	    $userId = $this->passport->getUserId();
	    list($count, $items) = Order::getItemsByUid($userId, $limit, $offset, $status);
        if ($count > 0) {
            foreach ($items as $index => $item) {
		        $productNo   = $item['productNo'];
                $productInfo = $productService->getProductDetail($productNo);
	            $items[$index]['cover']        = $productInfo['img'];
		        $items[$index]['createTime']   = date('Y-m-d H:i:s', $item['createTime']);
                $items[$index]['travelDay']    = date('Y-m-d H:i:s', $item['travelDay']);
                $items[$index]['payTime']      = $items[$index]['payTime']?date('Y-m-d H:i:s', $item['payTime']):'';
	            $items[$index]['refoundable']  = $productInfo['refoundable'];
	        }
        }
        return [$count, $items];        
    }

    // 保存订单
    public function saveOrder($linkMan, $linkPhone, $num, $custId) {

        $response = [
            'code'  => \OrderConst::API_RESULT_STATUS['missing'],
            'orderId' => 0,
            'msg'     => '商品不存在'
        ];

        $productService = new ProductService;
        $productInfo = $productService->getProductDetail($this->_productNo);

        if ($productInfo) {

            $thridService = new ThirdService;
            $thridService->setProductNo($this->_productNo);
            $saveThrid    = $thridService->saveOrder($this->_travateDate, [
                'linkMan'   => $linkMan,
                'linkPhone' => $linkPhone
            ], $num);

            if ($saveThrid['status'] == \OrderConst::THRID_RESULT_STATUS['success']) {

                $orderModel = new Order;
                $orderModel->travelDay = strtotime($this->_travateDate);
                $orderModel->updateTime   = time();
                $orderModel->orderId      = $saveThrid['orderId'];
                $orderModel->spreadPrize  = $productInfo['spreadPrize'];
                $orderModel->productNo    = $productInfo['productNo'];
                $orderModel->productName  = $productInfo['productName'];
                $orderModel->orderAccount = $this->passport->getUserId();
                $orderModel->num       = $num;
                $orderModel->linkMan   = $linkMan;
                $orderModel->linkPhone = $linkPhone;

                if ($custId) {
                    $orderModel->custId = $custId;
                }
                
                // 需要审核
                if ($productInfo['is_confirm'] == 1) {
                    $orderModel->status = \OrderConst::ORDER_STATUS['pending'];
                } else {
                    $orderModel->status = \OrderConst::ORDER_STATUS['wating'];
                }
 
                $orderModel->price           = $productInfo['customPrize'];
                $orderModel->salePrice       = $productInfo['salePrice'];
                $orderModel->SettlementPrice = $productInfo['SettlementPrice'];
                $orderModel->totalPrice      = $productInfo['customPrize'] * $num;
                $orderModel->createTime      = time();
                $orderModel->payMinute       = $productInfo['payMinute'];	
                $orderModel->payLimitTime    = $orderModel->createTime + ($productInfo['payMinute'] * 60);

                if ($orderModel->save()) {
                    return $response = [
                        'code'      => \OrderConst::API_RESULT_STATUS['success'],
                        'orderStatus' => $orderModel->status,
                        'orderId'     => $orderModel->id,
                        'msg'         => $saveThrid['msg']
                    ];
                }
		
                return $response = [
                    'code'  => \OrderConst::API_RESULT_STATUS['failed'],
                    'orderId' => 0,
                    'msg'     => '下单失败'
                ];
    
            }

            $response = $saveThrid;
        }

        return $response;
    }

    // 取消订单/退票
    public function cancelOrder($orderId) {

        $orderInfo = Order::getItemById($orderId);

        if ($orderInfo) {

            $isOwner = $this->checkOrderOwner($orderInfo);

            if ($isOwner) {

              $now = time();
              $orderStatus = $orderInfo->status;

              $isRefoundAble = $this->checkRefondAble($orderStatus);

              if (!$isRefoundAble) {
                   return [
                        'code'    => \OrderConst::API_ORDER_STATUS['unrefound'],
                        'msg'     => '订单无法退订'
                    ];
              }

              // 退款需要审核
              if ($orderStatus == \OrderConst::ORDER_STATUS['published']) {

                $orderInfo->status = \OrderConst::ORDER_STATUS['refoundApply'];

              } else {

                $orderInfo->status = \OrderConst::ORDER_STATUS['refoundConfirming'];

                $thridService = new ThirdService;
              
                $cancelOrder  = $thridService->cancelOrder($orderInfo->orderId);
                
                if (!$cancelOrder) {
                  return [
                      'code'  => \OrderConst::API_ORDER_STATUS['failed'],
                      'msg'     => $thridService->getErrMsg()
                    ];
                }
  
              }

              $orderInfo->updateTime = $now;
              
              if ($orderInfo->save()) {
                return [
                    'code'  => \OrderConst::API_ORDER_STATUS['success'],
                    'msg'     => '申请退票成功'
                ];
              }

            return [
                'code'  => \OrderConst::API_ORDER_STATUS['failed'],
                'msg'     => '退票失败, 数据库操作失败'
            ];

            } else {
                return [
                    'code'  => \OrderConst::API_ORDER_STATUS['permission'],
                    'msg'     => '无权操作'
                ];
            }
        }

        return [
            'code'  => \OrderConst::API_ORDER_STATUS['missing'],
            'msg'     => '订单不存在'
        ];;
    }

    // 匹配订单是否属于当前用户
    public function checkOrderOwner($orderObj) {
	if ($orderObj->orderAccount != $this->passport->getUserId()) {
            return false;
        }
        return true;
    }

    // 检查订单是否可退票
    private function checkRefondAble($orderStatus) {
        if ($orderStatus != 0 || $orderStatus != 1 || $orderStatus != 9) {
            return true;
        }
        return false;
    } 





}